<?php
namespace import;

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\IOFactory;

use app\admin\model\ExpressModel;

class Expressdata {
    public function import($file){
        try {
            // 转码
            // $file = iconv('utf-8', 'gb2312', $file);
    
            $reader = IOFactory::createReader('Xlsx');
            $reader->setReadDataOnly(true);
            $excel = $reader->load($file);
            $sheet = $excel->getSheet(0);
    
            // 获取总行数
            $rowCnt = $sheet->getHighestRow();
            $data = [];
    
            // 取出数据
            for ($row = 2; $row <= $rowCnt; $row++){
                $isEx = ExpressModel::where('billcode', $sheet->getCellByColumnAndRow(9, $row)->getValue())
                ->find();
                if(empty($isEx)){
                    $data[] = [
                        'phone'         => $sheet->getCellByColumnAndRow(2, $row)->getValue(),
                        'billcode'      => $sheet->getCellByColumnAndRow(9, $row)->getValue(),
                        'content'       => $sheet->getCellByColumnAndRow(6, $row)->getValue(),
                        'company'       => $sheet->getCellByColumnAndRow(7, $row)->getValue(),
                        'company_code'  => $sheet->getCellByColumnAndRow(8, $row)->getValue(),
                    ];
                }
            }
            if(!empty($data)){
                $express = new ExpressModel;
                $express->saveAll($data);
            }
            return count($data);
        } catch (\Exception $th) {
            throw $th;
            // return false;
        }
    }
}